<template>
  <div>
    <!-- 卡片视图区域 -->
    <el-card>
      <!-- 搜索与添加区域 -->
      <el-row :gutter="20">
        <!-- 输入框 -->
        <el-col :span="5" :offset="17">
          <el-input
            placeholder="输入工号查找"
            clearable
            type="sousuo"
            v-model="queryInfo.query"
            @clear="getuserlist"
          >
            <el-button
              slot="append"
              icon="el-icon-search"
              @click="search"
            ></el-button>
          </el-input>
        </el-col>
        <!-- 添加用户按钮 -->
        <el-col :span="1">
          <el-button type="goon" @click="showAddDialog"> 添加 </el-button>
        </el-col>
      </el-row>

      <!-- 用户列表区域 -->
      <el-table
        :data="
          userlist.slice((currentPage - 1) * pageSize, currentPage * pageSize)
        "
        border
        stripe
        :cell-style="{ 'text-align': 'center' }"
        :header-cell-style="{ 'text-align': 'center' }"
      >
        <el-table-column label="姓名" prop="name"> </el-table-column>
        <el-table-column label="工号" prop="account"> </el-table-column>
        <el-table-column label="电话" prop="phone"> </el-table-column>
        <el-table-column label="邮箱" prop="email"> </el-table-column>
        <el-table-column label="操作" width="180px">
          <template slot-scope="scope">
            <!-- 删除按钮 -->
            <el-button
              type="danger"
              size="mini"
              round
              @click="removeUser(scope.row.account)"
              >删除</el-button
            >
            <!-- 修改按钮 -->
            <el-button
              type="primary"
              size="mini"
              round
              @click="showEditDialog(scope.row)"
              >修改</el-button
            >
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页区域 -->
      <el-pagination
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
        :current-page="currentPage"
        :page-sizes="[8]"
        :page-size="pageSize"
        layout="total, sizes, prev, pager, next, jumper"
        :total="total"
      >
      </el-pagination>
    </el-card>

    <!-- 添加用户 -->
    <el-dialog
      title="学生负责人权限管理"
      :visible.sync="addDialogVisible"
      width="30%"
      center
      @close="addDialogClosed"
    >
      <el-form
        label-width="60px"
        :model="addForm"
        :rules="addFormrules"
        ref="addFormref"
      >
        <el-form-item label="姓名" prop="name">
          <el-input size="10%" v-model="addForm.name"></el-input>
        </el-form-item>
        <el-form-item label="工号" prop="account">
          <el-input v-model="addForm.account"></el-input>
        </el-form-item>
        <el-form-item label="电话" prop="phone">
          <el-input v-model="addForm.phone"></el-input>
        </el-form-item>
        <el-form-item label="邮箱" prop="email">
          <el-input v-model="addForm.email"></el-input>
        </el-form-item>
        <el-form-item label="密码" prop="password">
          <el-input v-model="addForm.password"></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="addDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="addUser()">确 定</el-button>
      </span></el-dialog
    >

    <!-- 修改提示框 -->
    <el-dialog
      title="学生负责人权限管理"
      :visible.sync="editDialogVisible"
      width="30%"
      center
    >
      <el-form
        label-width="60px"
        :model="editForm"
        :rules="editFormrules"
        ref="editFormref"
      >
        <el-form-item label="姓名" prop="name">
          <el-input v-model="editForm.name" disabled></el-input>
        </el-form-item>
        <el-form-item label="工号" prop="account">
          <el-input v-model="editForm.account" disabled></el-input>
        </el-form-item>
        <el-form-item label="电话" prop="phone">
          <el-input v-model="editForm.phone"></el-input>
        </el-form-item>
        <el-form-item label="邮箱" prop="email">
          <el-input v-model="editForm.email"></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="editDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="editUser">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
export default {
  data() {
    // 验证邮箱的规则
    var checkEmail = (rule, value, cb) => {
      // 验证邮箱的正则表达式
      const regEmail = /^([a-zA-Z0-9_-])+@([a-zA-Z0-9_-])+(\.[a-zA-Z0-9_-])+/;

      if (regEmail.test(value)) {
        return cb();
      }

      cb(new Error("请输入合法的邮箱！"));
    };

    // 验证手机号的规则
    var checkMobile = (rule, value, cb) => {
      // 验证手机号的正则表达式
      const regMobile =
        /^(0|86|17951)?(13[0-9]|15[012356789]|17[678]|18[0-9]|14[57])[0-9]{8}$/;
      // 手机号合法
      if (regMobile.test(value)) {
        return cb();
      }
      // 手机号不合法
      cb(new Error("请输入合法的手机号！"));
    };

    return {
      currentPage: 1,
      pageSize: 8,
      // 获取用户列表的参数对象
      queryInfo: {
        // 搜索关键字
        query: "",
        // 当前页数
        // pagenum: 1,
        // 当前每页显示多少条数据
        // pagesize: 2,
      },
      userlist: [],
      total: 0,
      editDialogVisible: false,
      addDialogVisible: false,
      // 添加用户的信息
      addForm: {
        name: "",
        account: "",
        phone: "",
        email: "",
        password: "",
      },
      // 添加用户的规则
      addFormrules: {
        name: [
          { required: true, message: "请输入用户名", trigger: "blur" },
          {
            min: 3,
            max: 10,
            message: "用户名长度在3~10个字符",
            trigger: "blur",
          },
        ],
        account: [
          { required: true, message: "请输入工号", trigger: "blur" },
          {
            min: 6,
            max: 11,
            message: "工号长度在6~11个字符",
            trigger: "blur",
          },
        ],
        phone: [
          { required: true, message: "请输入手机号", trigger: "blur" },
          { validator: checkMobile, trigger: "blur" },
        ],
        email: [
          { required: true, message: "请输入邮箱", trigger: "blur" },
          { validator: checkEmail, trigger: "blur" },
        ],
        password: [
          { required: true, message: "请输入密码", trigger: "blur" },
          {
            min: 6,
            max: 11,
            message: "密码长度在6~11个字符",
            trigger: "blur",
          },
        ],
      },
      // 修改用户的信息
      editForm: {},
      // 修改用户的规则
      editFormrules: {
        jobnum: [
          { required: true, message: "请输入工号", trigger: "blur" },
          {
            min: 6,
            max: 11,
            message: "工号长度在6~11个字符",
            trigger: "blur",
          },
        ],
        phone: [
          { required: true, message: "请输入手机号", trigger: "blur" },
          { validator: checkMobile, trigger: "blur" },
        ],
        email: [
          { required: true, message: "请输入邮箱", trigger: "blur" },
          { validator: checkEmail, trigger: "blur" },
        ],
      },
    };
  },
  created() {
    this.getuserlist();
  },
  methods: {
    async getuserlist() {
      const { data: res } = await this.$http.get("/api/student/showall");
      if (res.code !== 200) return this.$message.error("获取用户列表失败！");
      this.userlist = res.data;
      this.total = res.data.length;
    },
    // 修改按钮
    async showEditDialog(info) {
      const { data: res } = await this.$http.post("/api/student/showstudent", {
        account: info.account,
      });
      this.editForm = res.data[0];
      this.editDialogVisible = true;
    },
    // 确认修改   已添表单验证
    async editUser() {
      const ConfirmResult = await this.$confirm(
        "此操作将修改该用户信息, 是否继续?",
        "提示",
        {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning",
        }
      ).catch((err) => err);
      if (ConfirmResult !== "confirm") {
        return this.$message.info("已取消修改该用户信息！");
      }
      this.$refs.editFormref.validate(async (valid) => {
        if (!valid) return;
        const { data: res } = await this.$http.post(
          "/api/student/modify",
          this.editForm
        );
        if (res.code !== 200) {
          this.editDialogVisible = false;
          return this.$message.error("修改该用户信息失败！");
        }
        this.editDialogVisible = false;
        this.getuserlist();
        this.$message.success("修改该用户信息成功！");
      });
    },
    // 添加用户   已添表单验证
    addUser() {
      this.$refs.addFormref.validate(async (valid) => {
        if (!valid) return;
        const { data: res } = await this.$http.post(
          "/api/student/add",
          this.addForm
        );
        if (res.code !== 200) return this.$message.error("添加用户失败！");
        this.$message.success("添加用户成功！");
        this.addDialogVisible = false;
        this.getuserlist();
      });
    },
    showAddDialog() {
      this.addDialogVisible = true;
    },
    // 搜索用户
    async search() {
      const { data: res } = await this.$http.post("/api/student/showstudent", {
        account: this.queryInfo.query,
      });
      if (res.code !== 200) {
        return this.$message.error("查询设备失败!");
      }
      this.$message.success("查询设备成功!");
      this.userlist = res.data;
    },
    // 监听  pagesize 改变的事件
    handleSizeChange(val) {
      this.pageSize = val;
    },
    // // 监听 页码值 改变的事件
    handleCurrentChange(val) {
      this.currentPage = val;
    },

    // 根据id删除对应用户信息
    async removeUser(account) {
      console.log(account);
      const ConfirmResult = await this.$confirm(
        "此操作将永久删除该用户, 是否继续?",
        "提示",
        {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning",
        }
      ).catch((err) => err);
      if (ConfirmResult !== "confirm") {
        return this.$message.info("已取消删除");
      }
      const { data: res } = await this.$http.post("/api/student/delete", {
        account: account,
      });
      if (res.code !== 200) {
        return this.$message.error("删除用户失败！");
      }
      this.$message.success("删除用户成功！");
      this.getuserlist();
    },
    addDialogClosed() {
      this.$refs.addFormref.resetFields();
    },
  },
};
</script>

<style>
.el-button--goon {
  background: #20b2aa !important;
  color: #fafdfd !important;
  font-size: 14px !important;
}
.el-table-column {
  text-align: center;
}
.el-form-item {
  text-align: center;
}
</style>